import { Input, Form, Button } from "antd-mobile";

import { useMemo } from "react";
import axios from "axios";
import {usecountDow} from '../../hooks/useCountDown'
import { useNavigate } from "react-router-dom";

const Login = () => {
    const nav=useNavigate()
  const [form] = Form.useForm()
  const max = 60;
  const { count, startCountDown } = usecountDow(max);
  const content = useMemo(() => {
    if (count === max) return "获取验证码";
    return `${count}秒后重试`;
  }, [count]);

  const handleClick = () => {
    form.validateFields(['tel']).then(async ({ tel }) => {
      startCountDown();
      const resp = await axios.get('/api/login/code',{params:{tel}})
      console.log(resp.data.data)
      form.setFieldValue('telCode', resp.data.data)
  
    })
  }

  const onFinish = async (values) => {
    const resp = await axios.post('/api/login/tel',  values)
    console.log(resp.data)
    const { code, data, message } = resp.data;
    if(code === 200) {
      localStorage.setItem('token', data.token)
      localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
      nav('/')
    } else {

    }
  }

  return (
    <div>
      <h2 style={{ textAlign: "center", lineHeight: "60px" }}>手机号登录</h2>
      <Form
        onFinish={onFinish}
        form={form}
        footer={
          <Button type="submit" color="primary" block>
            登录
          </Button>
        }
      >
        <Form.Item layout="horizontal" label='手机号' rules={[{ required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }]} name="tel">
          <Input placeholder="请输入手机号"></Input>
        </Form.Item>
        <Form.Item
          name="telCode"
          layout="horizontal"
          label="验证码"
          rules={[{ required: true, message: '请输入验证码' }]}
          extra={
            <Button block disabled={count !== max} onClick={() => handleClick()}>
              {content}
            </Button>
          }
        >
          <Input placeholder="请输入验证码"></Input>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
